package com.sign2024.sign2024project.farenergy;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024project.farenergy.entry.Sample;
import com.sign2024.sign2024project.farenergy.entry.SampleTest;
import com.sign2024.sign2024project.farenergy.service.SampleService;
import com.sign2024.sign2024project.farenergy.service.SampleTestService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yujie
 * @data 2024/12/20 9:22
 */
@Component
public class FarEnergyController {

    private static String TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImY2NTkwZDg4ZjFmOTQxNjJhYjE3ODE5MWY1NDdiM2QzIn0.Lko3FXXfNATwMfzutvyegpO-9zApJFnuCEJJnvEKRQCnci5uf-qoNueRfALWp4uwygwBeo2yervBzfx8rlSZFA";

    @Resource
    private SampleService sampleService;

    @Resource
    private SampleTestService sampleTestService;

    // 开一个定时 任务 定时 获取 式样数据
    // 测试阶段 暂定 2 分钟 执行一次
//    @Scheduled(cron = "0 */2 * * * ?")
    public void farEnergyTask() {
        System.out.println(new Date() + " :测试");
        List<Integer> ordIdList = getSampleDistribute();
//        System.out.println(ordIdList);

        // 循环 试样分发 获取 相关试样分发编辑数据
        if (ordIdList.isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "试样分发数据为空");
        }

        for (Integer ordId : ordIdList) {
            JSONObject jsonObject = getSampleDistributeDetails(ordId, "未领样");
//            System.out.println(jsonObject);
            JSONObject data = (JSONObject) jsonObject.get("data");
//            System.out.println(data);
            if (data != null) {
//                boolean flag = data.containsKey("summaryInfos");
//                if (flag) {
//                    System.out.println("包含");
////                    JSONArray summaryInfos = jsonObject.getJSONArray("summaryInfos");
//                    Object summaryInfos = data.get("summaryInfos");
//                    System.out.println(summaryInfos);
//                }


                // 样品 详情列表
                JSONArray summaryInfos = data.getJSONArray("summaryInfos");
                for (Object item : summaryInfos) {
                    JSONObject record = (JSONObject) item;
//                    System.out.println(record);
//                    System.out.println("-----------------------------------------------------------------------------");

                    // 添加数据 
                    // 获取 summaryInfos ->  sampleInfos ->  results 数据
                    // 样品 名称 summaryInfos -> sampleInfos 下的 samName
                    JSONArray sampleInfos = record.getJSONArray("sampleInfos");
                    for (Object obj : sampleInfos) {
                        JSONObject sample = (JSONObject) obj;
                        String samName = (String) sample.get("samName");
//                        System.out.println("样品名称: " + ordId + " : " + samName);

                        // 样品 编号 samId   样品 id samNumber
                        Integer samId = (Integer) sample.get("samId");
//                        System.out.println("样品id: " + ordId + " : " + samId);

                        String samNumber = (String) sample.get("samNumber");
//                        System.out.println("样品编号: " + ordId + " : " + samNumber);

                        Sample sam = new Sample();
                        sam.setSamId(samId);
                        sam.setSamName(samName);
                        sam.setSamNumber(samNumber);
                        sampleService.insert(sam);

                        // 添加 样品试验任务表 数据
                        // 获取 summaryInfos ->  sampleInfos ->  results 数据
                        JSONArray results = sample.getJSONArray("results");
                        for (Object result : results) {
                            JSONObject tempResult = (JSONObject) result;
                            // 试样编号
                            String resNumber = (String) tempResult.get("resNumber");
                            // 试验名称
                            String resName = (String) tempResult.get("resName");
//                            System.out.println("resNumber: " + resNumber);
//                            System.out.println("resName: " + resName);
                            SampleTest sampleTest = new SampleTest();
                            sampleTest.setSampleTestCode(resNumber);
                            sampleTest.setTestName(resName);
                            // 样品id 样品编号
                            sampleTest.setSamId(samId);
                            sampleTest.setSamNumber(samNumber);
                            sampleTestService.insert(sampleTest);
                        }
                    }
                }

            }
        }

        System.out.println("执行结束");
    }

    /**
     * 获取 试样分发 数据
     * 试样分发 http://dev.njyn.shucantech.cn/api/orderInfo/search/1/50 数据 接口 post
     *
     * @return
     */
    public static List<Integer> getSampleDistribute() {
        String authorization = TOKEN;
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 添加 Authorization 头
        // 注意：这里假设 token 前需要加 "Bearer "
        headers.set("Authorization", "Bearer " + authorization);

        // 创建请求体 (JSON 数据)
//        String requestBody = "";
//        String requestBody = String.format("{\"isAsc\": \"%s\", \"ordStatus\": \"%s\", \"ordNumber\": %s, \"page\": %d, \"pageSize\": %d}",
//                false, "试样分发", "ordNumber", 1, 50);
        String requestBody = "{\n" +
                "  \"isAsc\": \"false\",\n" +
                "  \"ordStatus\": \"试样分发\",\n" +
                "  \"orderBy\": \"ordNumber\",\n" +
                "  \"page\": 1,\n" +
                "  \"pageSize\": 50\n" +
                "}";

        // 封装请求体和请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        Integer pageNum = 1;
        Integer pageSize = 50;

        // 发送 POST 请求
        String baseUrl = "http://dev.njyn.shucantech.cn/api/orderInfo/search";
        String url = baseUrl + "/" + pageNum + "/" + pageSize;
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

        // 打印响应体
        String responseBody = response.getBody();
        // 使用 FastJSON 解析 JSON 响应体
        JSONObject jsonObject = JSON.parseObject(responseBody);

        JSONObject data = (JSONObject) jsonObject.get("data");
        JSONArray array = data.getJSONArray("list");

        // 返回一个 ordId 集合
        List<Integer> ordIdList = new ArrayList<>();
        for (Object item : array) {
            // 将每个 item 转换为 JSONObject
            JSONObject record = (JSONObject) item;
            Integer ordId = Integer.valueOf(record.getString("ordId"));
            ordIdList.add(ordId);
        }

        return ordIdList;
    }

    /**
     * 获取 相关试样分发编辑数据  post 接口
     * http://dev.njyn.shucantech.cn/api/orderInfo/resultByStatus
     *
     * @param ordId  试样 id
     * @param status 状态 例如 未领样
     */
    public static JSONObject getSampleDistributeDetails(Integer ordId, String status) {
        String authorization = TOKEN;
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 添加 Authorization 头
        // 注意：这里假设 token 前需要加 "Bearer "
        headers.set("Authorization", "Bearer " + authorization);

        // 创建请求体 (JSON 数据)
        String requestBody = String.format("{\"ordId\": \"%d\", \"status\": \"%s\"}", ordId, status);

        // 封装请求体和请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送 POST 请求
        String url = "http://dev.njyn.shucantech.cn/api/orderInfo/resultByStatus";
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

        String responseBody = response.getBody();
        JSONObject jsonObject = JSON.parseObject(responseBody);
//        System.out.println(jsonObject);
//        JSONObject data = (JSONObject) jsonObject.get("data");
//        return data;
        return jsonObject;

    }
}
